package com.ctf.soft.ms.core;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 名称： ExceptionHandlerResolver<br>
 * 描述： 异常处理<br>
 * 最近修改时间：2015-07-22 10:00:00<br>
 * 修改说明：
 *
 * @author zhu
 */
public class ExceptionHandlerResolver extends SimpleMappingExceptionResolver {

    private Logger log = LoggerFactory.getLogger(ExceptionHandlerResolver.class);


    @Override
    protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        log.info("system exception:", ex);
        /*判断是否是Ajax请求*/
        if (!isAjax(request))
            return super.doResolveException(request, response, handler, ex);

        View view = new MappingJackson2JsonView();
        ModelAndView mv = new ModelAndView();
        mv.setView(view);
        //mv.addObject(new ResponseMsg(false, ex.getMessage()));
        return mv;
    }

    private boolean isAjax(HttpServletRequest request) {
        return "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
    }
}
